﻿using System;
using System.Web;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.Abstractions;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax
{
    public abstract class AjaxHandler : IHttpHandler
    {
        protected AjaxHandler(Bootstrapper bootstrapper)
        {
            Bootstrapper = bootstrapper;
        }

        #region / Properties /

        private Bootstrapper Bootstrapper { get; set; }

        public bool IsReusable
        {
            get { return false; }
        }

        #endregion

        #region / Methods /

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var requestContext = new RequestContext(context);

                Bootstrapper.Init(requestContext);
                var controller = Bootstrapper.ControllerFactory.CreateController(requestContext);
                if (controller != null)
                    controller.Execute(requestContext);
            }
            catch (Exception e)
            {
                context.Response.Write(e.Message);
                context.Response.Write(e.StackTrace);
                context.Response.StatusCode = 500;
            }
            finally
            {
                context.Response.End();
            }
        }

        #endregion
    }
}